<template>
    <div :class="['button', disabled ? 'disabled' : '']" @[handleEvent]="handleClick" ref="button">
        <slot></slot>
    </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue';

const emits = defineEmits(['click'])

const props = defineProps({
    disabled: {
        default: false,
        type: Boolean
    }
})

const hasListen = ref(false)

const button = ref(null)

const handleEvent = ref('click')

const isMobile = () => {
    const whitelist = ['iPhone', 'Android']
    let isPhone = false
    for (let i = 0; i < whitelist.length; i++) {
        if (navigator.userAgent.indexOf(whitelist[i]) > -1) {
            isPhone = true
            break
        }
    }
    return isPhone

}

const handleClick = (e) => {
    if (!props.disabled) {
        if (isMobile()) {
            e.preventDefault()
            if (!hasListen.value) {
                hasListen.value = true
                button.value.addEventListener('touchend', handleTouchEnd)
            }
        } else {
            emits('click')
        }
    }
}

const handleTouchEnd = () => {
    emits('click')
}

onMounted(() => {
    isMobile() && (handleEvent.value = 'touchstart')
})

onUnmounted(() => {
    hasListen.value && button.value.removeEventListener('touchend', handleTouchEnd)
})

</script>

<style >
.button {
    display: inline-block;
    border: 1px solid #0bf;
    color: #0bf;
    padding: 5px 10px;
    cursor: pointer;
}

.disabled {
    color: #999;
    border: 1px solid #999;
    background-color: #ccc;
    cursor: not-allowed;
}
</style>